//
//  JRAccountViewModel.swift
//  myWeibo
//
//  Created by 樊健荣 on 16/7/21.
//  Copyright © 2016年 樊健荣. All rights reserved.
//

import UIKit

//ViewModel的作用是,因为控制器内代码太多,日后维护不方便,采用MVVM设计模式,将控制器中的一些逻辑性代码抽取出来,例如网络请求,沙盒存储等
class JRAccountViewModel: NSObject {

    ///单例
    static let sharedAccountViewModel: JRAccountViewModel = JRAccountViewModel()
    ///登录帐号信息
    var account: JRAccountModel?
    
    ///给一个外部属性判断是否登录
    var isLogin: Bool {
        get{
            return account != nil
        }
    }
    
    /// 账号保存的路径
    let accountFile = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last!.stringByAppendingString("/account.plist")
    
    /********************************Method*********************************/
    
     // MARK: - Method
    override init() {
        super.init()
        //每当创建VM就会进入这个方法个登录帐号赋值,--->判断有没有值
        account = loadAccount()
    }
     
     
    ///从Oauth控制器中抽取出来的网络请求方法
    func loadToken(code: String) {
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        //请求token
        let parameters = [
            "client_id" : client_id,
            "client_secret" : client_secret,
            "grant_type" : "authorization_code",
            "code" : code,
            "redirect_uri" : redirect_uri
        ]
        
        //请求accepttoken
        JRNetWorkTool.sharedNetWorkTool.POST(urlString, parameters: parameters, progress: nil, success: { (_, responseObject) -> Void in
            //得到token
            print("\(responseObject)")
            //将得到的responseObject用一个模型存储起来,
            let accountModel = JRAccountModel(dic: responseObject as! [String : AnyObject])
            
            self.account = accountModel
            
            
            
            //将其归档
            NSKeyedArchiver.archiveRootObject(self.account!, toFile: self.accountFile)
            
            
            }) { (_, error) -> Void in
                print("error")
        }
    }
    ///从沙盒中读取帐号
    private func loadAccount() -> JRAccountModel? {
        
        //从沙盒中读取数据
        let account =  NSKeyedUnarchiver.unarchiveObjectWithFile(self.accountFile) as? JRAccountModel
        
        //如果沙盒中读取的数据有值,且没有过期
        if account != nil && account?.expiresDate?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
            
            return account
        }
        return nil
    }
    
}
